import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {IndexService} from "../../services/index.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-shop-cart-nav',
  templateUrl: './shop-cart-nav.component.html',
  styleUrls: ['./shop-cart-nav.component.css']
})
export class ShopCartNavComponent implements OnInit {

  @Input() shoppingShow: boolean;
  @Output() shopNav = new EventEmitter();
  @Input() addOrderId:string;

  selectFoodCount: number = 0;
  countPrice = 0;

  constructor(
    private indexService: IndexService,
    private router: Router
  ) {
  }


  // 计数
  countNumber(res) {
    this.selectFoodCount = 0;
    this.countPrice = 0;
    res.forEach(v => {
      this.selectFoodCount += v.count;
      v.foodList.forEach(v1 => {

        if (v1.type == '0') {
          if (v1.count) {
            this.countPrice += (v1.price * v1.count);
          }
        } else if (v1.type == '1') {
          v1.typeList.radioType.forEach(v2 => {
            this.countPrice += v2.count * v2.price;
          });

        }
        else if (v1.type == '2') {
          v1.typeList.multiType.forEach(v2 => {
            this.countPrice += v2.count * v1.price;
          });
        }
        else if (v1.type == '3') {
          v1.typeList.pumpType.forEach(v2 => {
            this.countPrice += v2.count * v1.price;
          });
        }
      });
    });

    // 一个bug没有找见，先这样处理
    if (!this.selectFoodCount) {
      this.countPrice = 0;
    }
  }

  ngOnInit() {

    // 订阅已选菜品列表，显示小图标中的数量
    this.indexService.foodAllEmit.subscribe(res => {
      this.countNumber(res);
    });

    if (!this.selectFoodCount) {
      this.countNumber(this.indexService.getData());
    }
  }

  // 购物车小图标
  stateChange() {
    if (this.selectFoodCount) {
      this.shopNav.emit(!this.shoppingShow);
    } else {
      this.shopNav.emit(false);
    }
  }

  // 选桌
  selectTable() {
    if (this.selectFoodCount > 0) {
      this.router.navigate(['/main/table/table-list'], {queryParams: {mark: 'choose-table'}}); // 标记mark进入餐桌列表/表示在下单选桌
    }
  }

  // 下单
  placeOrder() {
    if (this.addOrderId) {
      this.router.navigate(['/main/order/order-submit'], {queryParams: {'addOrderId': this.addOrderId}});
    }
  }

}
